from coding.API.coding_class import CodingManager
from gitlab.API.gitlab_class import GitLabManager

project_name = "xn"  #设置同步项目
## gitlab认证信息设置
GITLAB_ACCESS_TOKEN = 'glpat--AR67THD'
GITLAB_URL = 'http://192.168.3.5'
## coding认证信息设置
TOKEN_USER = 'HQHholeUMj'    #GITLAB远程镜像使用
CODING_ACCESS_TOKEN = '6fbd7ec91bdbc77'  #GITLAB远程镜像使用，CODING API使用
CODING_ACCESS_URL = 'https://wangwuli.coding.net'   #组织的coding地址

## coding部分
# 创建coding实例  
coding_manager = CodingManager(CODING_ACCESS_TOKEN, CODING_ACCESS_URL)

# 查询项目信息
project_info = coding_manager.get_project_list(project_name=project_name)

# 使用项目ID查询仓库列表信息
repository_info = coding_manager.get_project_git_repository(project_info['Response']['Data']['ProjectList'][0]['Id'])

# 根据仓库列表项总数信息，再次传参，获取所有仓库信息
repository_all_info = coding_manager.get_project_git_repository(
    project_info['Response']['Data']['ProjectList'][0]['Id'],
    page_size=repository_info['Response']['DepotData']['Page']['TotalPage']
    )

depots = repository_all_info['Response']['DepotData']['Depots']  #返回的仓库列表

## gitlab部分
# 创建 GitLabManager 实例  
gitlab_manager = GitLabManager(GITLAB_ACCESS_TOKEN, GITLAB_URL)

# 找到组ID
gitlab_group_id = ""
groups_response = gitlab_manager.get_groups()
for groups_response_one in groups_response:
    if groups_response_one["name"] == project_name:
        gitlab_group_id = groups_response_one["id"]
        break
if not gitlab_group_id:
    group_info = gitlab_manager.create_groups(project_name)  #没有找到项目，创建项目
    gitlab_group_id = group_info['id']
    # print("因为群组层级关系，请在需要的层级，手动创建项目")

for depots_one in depots:
    # 远程镜像地址
    mirror_url = f'https://{TOKEN_USER}:{CODING_ACCESS_TOKEN}@e.coding.net/sumztech/xn/{depots_one["Name"]}.git'

    # 创建仓库
    project_info = gitlab_manager.create_project(depots_one["Name"], gitlab_group_id, visibility='private')
    print(project_info)
    if project_info:
    # 配置远程镜像
        mirror_info = gitlab_manager.project_conf_pull_mirror(project_info['id'], mirror_url)
        print(mirror_info)